# ！/usr/bin/ python3
# -*- codeing = utf-8 -*-
# @Time :2022/1/2 20:02
# @Author:wuhha
# @File : utils.py
# 一些工具方法或类的抽取
from functools import wraps
from django.contrib import messages
from django.core.exceptions import PermissionDenied
from django.http import HttpResponseBadRequest
from django.shortcuts import render
from django.views import View

from youpu.models import User


def youpu_login_required(view_method):
    @wraps(view_method)
    def inner(request, *args, **kwargs):
        # 根据session中携带的信息查出user
        is_login = request.session.get('IS_LOGIN', False)
        username = request.session.get('uname', "")
        if ((not is_login) or username == ""):
            # cookie中不含相关信息，直接跳回登录界面
            messages.info(request, "请先进行登录！")
            return render(request, "youpu/users/login.html")
        else:
            # 用户已经登录，根据username查出user放到request中
            request.user = User.objects.get(username=username)
            return view_method(request, *args, **kwargs)
    return inner


# 让consumer类的scope中也注有user【代替AuthMiddlewareStack】
# 由于consumer的方法是异步的，所以此处对装饰器做点特殊处理
# 为了让装饰器获得self的值，将装饰器和被装饰方法写在同一个类里
# def youpu_login_required_forconsumer(consumer_method):
#     @wraps(consumer_method)
#     async def inner(self, *args, **kwargs):
#         # 根据session中携带的信息查出user【能够进入发送私信界面，说明一定已经登录了】
#         username = self.scope["session"].get('uname', "")
#         # 根据username查出user放到request中
#         self.scope["user"] = User.objects.get(username=username)
#         result = await consumer_method(self, *args, **kwargs)
#         return result
#     return inner

def ajax_required(f):
    """验证是否为AJAX请求"""

    @wraps(f)
    def wrap(request, *args, **kwargs):
        #  request.is_ajax() 方法判断是否是 ajax 请求
        # 参考:https://code.ziqiangxuetang.com/django/django-ajax.html
        if not request.is_ajax():
            return HttpResponseBadRequest("不是AJAX请求！")
        return f(request, *args, **kwargs)

    return wrap


class AuthorRequiredMixin(View):
    """
    验证是否为原作者，用于状态删除、文章编辑；
    个人中心模块中更新信息不要验证是否为原作者，因为UserUpdateView返回的是当前登录用户的form
    """
    def dispatch(self, request, *args, **kwargs):
        # 状态和文章实例有user属性
        if self.get_object().user.username != self.request.user.username:
            raise PermissionDenied
        return super(AuthorRequiredMixin, self).dispatch(request, *args, **kwargs)